#version 330 core
out vec4 FragColor;

in vec2 TexCoords;

uniform sampler2D shadowMap;
uniform sampler2D DistanceMap;
uniform sampler2D NorMap;

uniform bool horizontal;
uniform float weight[5] = float[] (0.2270270270, 0.1945945946, 0.1216216216, 0.0540540541, 0.0162162162);

void main()
{            
    vec3 dist = texture(DistanceMap, TexCoords).rgb;
    float penumbra = dist.x*(1.0 - dist.y);
    vec3 normal = texture(NorMap, TexCoords).rgb;
    vec2 tex_offset = 1.0 / textureSize(shadowMap, 0) * penumbra * 1200; // gets size of single texel
    vec3 result = texture(shadowMap, TexCoords).rgb * weight[0];


    if(dist.z > 0.5)
    {
        if(horizontal)
        {
            float cosang = clamp(1.0 - dot(vec3(1,0,0),normalize(normal)), 0.2, 1.0);
            tex_offset *= cosang;
            for(int i = 1; i < 5; ++i)
            {
                result += texture(shadowMap, TexCoords + vec2(tex_offset.x * i, 0.0)).rgb * weight[i];
                result += texture(shadowMap, TexCoords - vec2(tex_offset.x * i, 0.0)).rgb * weight[i];
            }
        }
        else
        {
            float cosang = clamp(1.0 - dot(vec3(0,1,0),normalize(normal)), 0.2, 1.0);
            tex_offset *= cosang;
            for(int i = 1; i < 5; ++i)
            {
                result += texture(shadowMap, TexCoords + vec2(0.0, tex_offset.y * i)).rgb * weight[i];
                result += texture(shadowMap, TexCoords - vec2(0.0, tex_offset.y * i)).rgb * weight[i];
            }
        }
    FragColor = vec4(result, 1.0);
    }    
}